package xyz.shenmegui.foodcheckserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.shenmegui.foodcheckserver.DO.Compound;
import xyz.shenmegui.foodcheckserver.mapper.CompoundMapper;
import xyz.shenmegui.foodcheckserver.service.CompoundService;
import xyz.shenmegui.foodcheckserver.utils.ObjectUtil;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CompoundServiceImpl implements CompoundService {

    @Autowired
    private CompoundMapper compoundMapper;

    @Override
    public List<Compound> selectByName(String name) {
        return compoundMapper.selectList(new QueryWrapper<Compound>().like("name", name));
    }

    @Override
    public List<Compound> selectByEnName(String enName) {
        return compoundMapper.selectList(new QueryWrapper<Compound>().like("en_name", enName));
    }

    @Override
    public Compound selectByNameE(String name) {
        return compoundMapper.selectOne(new QueryWrapper<Compound>().eq("name", name));
    }

    @Override
    public Compound selectByEnNameE(String enName) {
        return compoundMapper.selectOne(new QueryWrapper<Compound>().eq("en_name", enName));
    }

    @Override
    public Compound selectById(String id) {
        return compoundMapper.selectOne(new QueryWrapper<Compound>().eq("id", id));
    }

    @Override
    public List<Compound> selectByIds(String ids) {
        ArrayList<Compound> compounds = new ArrayList<>();
        if (ObjectUtil.isNull(ids)) {
            return compounds;
        }
        String[] id_array = ids.split(",");
        for (String id : id_array) {
            Compound compound = compoundMapper.selectOne(new QueryWrapper<Compound>().eq("id", id));
            compounds.add(compound);
        }
        return compounds;
    }

    @Override
    public int insert(Compound compound) {
        return compoundMapper.insert(compound);
    }

    @Override
    public List<Compound> selectTop10() {
        QueryWrapper<Compound> nums = new QueryWrapper<Compound>().orderByDesc("nums").last("limit 10");
        return compoundMapper.selectList(nums);
    }

    @Override
    public int updateCompounds(List<Compound> compounds) {
        int success = 0;
        for (Compound compound : compounds) {
//            System.out.println(compound);
            success += compoundMapper.updateById(compound);
        }
        return success;
    }

}
